package com.xubeizhi.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xubeizhi.common.Result;
import com.xubeizhi.entity.User;
import com.xubeizhi.mapper.UserMapper;
import com.xubeizhi.service.UserService;
import com.xubeizhi.utils.DataUtils;
import com.xubeizhi.utils.JwtUtil;
import com.xubeizhi.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 登录方法
     * @param user
     * @return
     */
    @Override
    public Result login(User user) {
//        BeanUtils.copyProperties(user,User.class);
        String username = user.getUsername();
        String password = user.getPassword();

        User dto = baseMapper.selectUsernameAndPassword(username, password);
        if (dto == null){
            return Result.error(1,"帐号为空，请检查你的帐号",null);
        }
        //校验密码
        if (password.equals(dto.getPassword())){
            Map<String,Object> claims = new HashMap<>();
            claims.put(dto.getUsername(), username);
            String token = JwtUtil.genToken(claims);
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token,token);
            return Result.success(0,"登录成功",null);

        }
        return Result.error(1,"密码错误",null);
    }

    /**
     * 注册用户接口
     * @param user
     * @return
     */
    @Override
    public Result register(User user) {
        BeanUtils.copyProperties(user,User.class);

        user.setCreateTime(DataUtils.getDateNow());
        user.setUpdateTime(DataUtils.getDateNow());
        if (user != null){
            baseMapper.insert(user);
        }else {
            return Result.success(1,"操作失败",null);
        }
        return Result.success(0,"注册成功",0);
    }

    @Override
    public Result getUserInfo(Integer id) {
        User user = baseMapper.selectById(id);
        if (user != null){
            return Result.success(0,"操作成功",user);
        }
            return Result.error(1,"操作失败",null);
    }

    @Override
    public Result updateUser(User user) {

        user.setUpdateTime(DataUtils.getDateNow());
        int rows = baseMapper.updateById(user);
        return rows > 0 ? Result.success(0,"操作成功",user) : Result.error(1,"操作失败",null);
    }

    @Override
    public Result getEmail() {
        List<UserVo> users = baseMapper.selectUsers();
        if (users != null){
            return Result.success(0,"操作成功",users);
        }
        return Result.error(1,"操作失败",null);
    }

}
